// deploy-services project main.go
package main

import (
	"flag"
	"os"
	"path/filepath"
	"runtime"

	"github.com/deploy-services/v2/log"
	"github.com/sevlyar/go-daemon"

	"github.com/deploy-services/v2/KolonseWeb"
	"github.com/deploy-services/v2/api"

	"github.com/deploy-services/v2/services"
)

var port = flag.Int("p", 10802, "-p service port")

func serve() {
	services.Load()
	KolonseWeb.DefaultApp.SetLogger(log.Logger())
	api.Load(KolonseWeb.DefaultApp)
	KolonseWeb.DefaultApp.Listen("0.0.0.0", *port)
}

func get_curdir() (string, error) {
	exePath := os.Args[0]
	absPath, err := filepath.Abs(exePath)
	if err != nil {
		return "", err
	}
	// 获取所在目录
	dir := filepath.Dir(absPath)
	return dir, nil
}

func main() {
	var enable_daemon bool
	flag.BoolVar(&enable_daemon, "D", false, "-D daemon,not support windows")
	flag.Parse()
	if runtime.GOOS == "windows" {
		enable_daemon = false
	}

	if !enable_daemon {
		serve()
		return
	}
	dir, err := get_curdir()
	if err != nil {
		log.Println("切换工作目录失败:", err)
		return
	}
	err = os.Chdir(dir)
	if err != nil {
		log.Println("切换目录失败:", err)
		return
	}
	cntxt := &daemon.Context{
		PidFileName: "deploy-services.pid",
		PidFilePerm: 0644,
		LogFileName: "deploy-services.log",
		LogFilePerm: 0640,
		WorkDir:     dir,
		Umask:       027,
		Args:        []string{"deploy-services daemon"},
	}

	d, err := cntxt.Reborn()
	if err != nil {
		log.Println("Unable to run: ", err)
		return
	}
	if d != nil {
		return
	}
	defer cntxt.Release()

	log.Println("- - - - - - - - - - - - - - -")
	log.Println("daemon started")

	go serve()

	err = daemon.ServeSignals()
	if err != nil {
		log.Println("Error:", err)
	}
	log.Println("daemon terminated")
}
